<template>
    <div class="dynamic-data-analysis" v-loading="loading" loading-text="加载数据中...">
        <div class="filter-container">
            <CustomDatePicker v-model="dateRange" :max-days="4" :disabled="loading"></CustomDatePicker>
            <el-button @click="handleReset" type="danger" :disabled="loading">重置</el-button>
        </div>
        <BaseChart ref="chart" :options="chartOption"></BaseChart>
    </div>
</template>

<script setup>
import { getMeterDetailApi } from '@/api/meter';
import BaseChart from '@/components/chart/BaseChart.vue';
import { watchEffect, ref, computed } from 'vue'
import dayjs from 'dayjs'
import CustomDatePicker from '@/components/header/CustomDatePicker.vue';

let loading = ref(false)
let chart = ref(null)

let props = defineProps({
    currentMeter: {
        type: Object,
        required: true
    }
})

// 时间范围
const defautTimeRange = [
    dayjs().subtract(2, 'day').startOf('day').valueOf(),
    dayjs().subtract(5, 'minute').valueOf()
];
const dateRange = ref(defautTimeRange);

let meterData = ref([])
const chartOption = computed(() => {
    return {
        title: "",
        xAxisData: meterData.value.map(item => item.time),
        yAxisUnit: "kWh",
        series: [{
            name: "用电量",
            type: 'line',
            data: meterData.value.map(item => item.usage),
            showExtremum: true
        }],
        showMarkLine: true,
        iszoom: true,
        isMerge: false,
    }
})

// 处理数据，计算用量
function processData(data) {
    if (!Array.isArray(data) || data.length === 0) return [];

    // 按时间排序，确保计算用量的顺序正确
    const sortedData = data.sort((a, b) => dayjs(a.time).valueOf() - dayjs(b.time).valueOf());

    return sortedData.map((item, index) => {
        const prevReading = index > 0 ? sortedData[index - 1].value : null;
        const usage = prevReading !== null ? Number(item.value) - Number(prevReading) : null;

        return {
            time: dayjs(item.time).format('MM-DD HH:mm'),
            usage: usage !== null ? Number(usage.toFixed(2)) : null,
        };
    });
}

const fetchMeterData = async () => {
    if (!props.currentMeter?.id) return

    loading.value = true
    try {
        let res = await getMeterDetailApi({
            id: props.currentMeter.id,
            start_time: dateRange.value[0],
            end_time: dateRange.value[1]
        })

        if (res.code !== 200) {
            ElMessage.error(res.message || '动态数据分析失败')
            console.error(res)
            return
        }

        meterData.value = processData(res.meter_readings || [])

    } catch (error) {
        console.error(error)
        ElMessage.error('服务器异常，动态数据分析失败')
    } finally {
        loading.value = false
    }
}

function handleReset() {
    dateRange.value = defautTimeRange;
}

watchEffect(() => {
    if (props.currentMeter?.id) {
        fetchMeterData()
    }
})
</script>

<style scoped>
.dynamic-data-analysis {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
}

.filter-container {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.2rem;
    flex-shrink: 0;
}

:deep(.vxe-table) {
    flex: 1;
    overflow: auto;
}
</style>